package com.bobo.swing;

import java.awt.Color;
import java.awt.Graphics;
import java.util.Random;

import javax.swing.JFrame;

/**
 * 窗口化程序（Swing实现绘制不同随机颜色）
 * @author win7
 *
 */
public class ColorSwingTest extends JFrame{

	private Thread t;
	//定义颜色数组
	private static Color[] color={Color.BLACK,Color.BLUE,Color.CYAN,Color.GREEN,Color.ORANGE,Color.YELLOW,Color.RED,Color.PINK,Color.LIGHT_GRAY};
	//实例化Random对象
	private static final Random random=new Random();
	
	private static Color GetColor(){
		return color[random.nextInt(color.length)];//生成一个颜色数组之内的颜色
	}
	
	public ColorSwingTest(){
		 t=new Thread(new Runnable() { //定义匿名内部类 实现Runnable接口
		   int x=30;
		   int y=60;
			public void run() {
				while(true){
					try {
						Thread.sleep(100);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					//获取组件绘图上下文对象
					Graphics graphics=getGraphics();
					graphics.setColor(GetColor()); //设置绘图颜色
					//绘制直线并递增垂直坐标
					graphics.drawLine(x, y, 100, y++);
					if(y>=80){
						y=50;
					}
				}
			}
		});
	   t.start();	 
	}
	
	//初始化程序界面的方法
	public static void init(JFrame jf,int x,int y){
		jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		jf.setSize(x,y);
		jf.setVisible(true);
	}
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		init(new ColorSwingTest(),100,100);
	}

}
